package com.lang.aspect.response;

import com.lang.response.PlatformResult;
import com.lang.response.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * creat by SimonLang
 * 2022/12/28 18:17
 */

@Component
@ControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 确保Controller都有@ResponseResult注解
        return returnType.hasMethodAnnotation(ResponseResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body == null){
            return PlatformResult.SUCCESS();
        }
        return PlatformResult.SUCCESS(body);
    }
}

